// pages/record/index.js
const app = getApp();
const { get, post } = require('../../utils/request');
const { formatDate } = require('../../utils/util');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        sportCalories: 0,
        mealCalories: 0,
        todayWeight: null,
        todaySleep: null,
        lastWeightRecord: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getTodayRecords();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getTodayRecords();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.getTodayRecords().then(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 获取今日所有记录
    async getTodayRecords() {
        try {
            // 获取今天的日期
            const today = formatDate(new Date());
            
            // 获取今日体重记录
            const weightRes = await get('/records/weight', {
                page: 1,
                pageSize: 1,
                date: today
            });
            
            const lastWeightRecord = weightRes.records && weightRes.records.length > 0 
                ? weightRes.records[0] 
                : null;

            // 获取其他记录
            const records = await get('/records/today');
            
            this.setData({
                sportCalories: records.sportCalories || 0,
                mealCalories: records.mealCalories || 0,
                todaySleep: records.sleep,
                lastWeightRecord: lastWeightRecord,
                todayWeight: lastWeightRecord ? lastWeightRecord.weight : null
            });
        } catch (error) {
            console.error('获取记录失败:', error);
        }
    },

    // 添加运动记录
    addSportRecord(e) {
        const type = e.currentTarget.dataset.type;
        wx.navigateTo({
            url: `/pages/record/sport?type=${type}`
        });
    },

    // 添加饮食记录
    addMealRecord() {
        wx.navigateTo({
            url: '/pages/record/meal'
        });
    },

    // 添加体重记录
    async addWeightRecord() {
        wx.navigateTo({
            url: '/pages/record/weight'
        });
    },

    // 添加睡眠记录
    async addSleepRecord() {
        wx.navigateTo({
            url: '/pages/record/sleep'
        });
    },

    // 查看运动记录详情
    viewSportRecords() {
        wx.navigateTo({
            url: '/pages/record/sport-list'
        });
    },

    // 查看饮食记录详情
    viewMealRecords() {
        wx.navigateTo({
            url: '/pages/record/meal-list'
        });
    }
})